import {
  Controller,
  Body,
  Post,
  Get,
  Request,
  BadRequestException,
  UseGuards,
  Query,
  Delete,
  Param,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { SearchUserDto } from './dto/search-user.dto';
import { DeleteUserDto } from './dto/delete-user.dto';
import { JwtAuthGuard } from 'src/auth/guard/jwt-auth.guard';
import { Roles } from 'src/rbac/role.decorator';
import { Role } from 'src/rbac/role.enum';

@ApiTags('用户')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @ApiOperation({ summary: '创建用户' })
  @Post('create')
  @Roles(Role.CreateUser)
  async createUser(@Body() createUserDto: CreateUserDto) {
    const user = await this.userService.findOneByName(createUserDto.username);
    if (user) {
      throw new BadRequestException({ msg: '此用户已存在~', success: 0 });
    }
    const result = await this.userService.createUser(createUserDto);
    if (result) return { msg: '创建成功！', success: 1, data: result };
    return { msg: '创建失败', success: 0 };
  }

  @ApiOperation({ summary: '获取用户信息' })
  @Get('info')
  async getUserInfo(@Request() req) {
    const user = await this.userService.findOneByName(req.user.username);
    return { msg: '查询成功！', success: 1, data: user };
  }

  @ApiOperation({ summary: '获取用户列表' })
  @Get('list')
  @Roles(Role.ViewUser)
  async getUserList() {
    const userList = await this.userService.findUserList();
    return { msg: '查询成功！', success: 1, data: userList };
  }

  @ApiOperation({ summary: '条件搜索用户' })
  @Get('search')
  @Roles(Role.ViewUser)
  async searchUsers(@Query() searchUserDto: SearchUserDto) {
    const userList = await this.userService.findUserByNameOrEmail(
      searchUserDto,
    );
    return { msg: '查询成功！', success: 1, data: userList };
  }

  @ApiOperation({ summary: '删除用户' })
  @Delete(':username')
  @Roles(Role.DeleteUser)
  async deleteUserById(@Param() deleteUserDto: DeleteUserDto) {
    await this.userService.removeUser(deleteUserDto.username);
    return { msg: '删除成功！', success: 1 };
  }
}
